//package com.plian.system.service.hr.employment.impl;
//
//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.ExcelWriter;
//import com.alibaba.excel.write.metadata.WriteSheet;
//import com.alibaba.excel.write.metadata.fill.FillConfig;
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.cache.UserCache;
//import com.plian.system.common.status.CheckStatus;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.dto.hr.employment.EmploymentPlanDTO;
//import com.plian.system.entity.hr.employment.EmployementPlan;
//import com.plian.system.entity.hr.employment.EmploymentDetail;
//import com.plian.system.entity.sys.ApprovalMessage;
//import com.plian.system.excel.ExcelExportUtil;
//import com.plian.system.mapper.hr.employment.EmploymentPlanMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ListResult;
//import com.plian.system.model.R;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.search.TokenSearch;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.service.hr.employment.IEmploymentDetailService;
//import com.plian.system.service.hr.employment.IEmploymentPlanService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.message.IApprovalMessageService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.hr.employment.EmploymentPlanExcelVO;
//import com.plian.system.vo.hr.employment.EmploymentPlanVO;
//import com.plian.system.vo.report.HeaderVO;
//import com.plian.system.vo.report.ReportReturnVO;
//import com.plian.system.vo.report.ReportVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.hr.employment.EmploymentPlanWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.web.bind.annotation.RequestBody;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.net.URLEncoder;
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.GZW_TYPE;
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
//@Service
//@Slf4j
//@AllArgsConstructor
//public class EmploymentPlanServiceImpl extends BaseServiceImpl<EmploymentPlanMapper, EmployementPlan> implements IEmploymentPlanService, BaseFlowService {
//    private IFormCodeService formCodeService;
//
//    private IEmploymentDetailService employmentDetailService;
//
//    private EmploymentPlanWrapper employmentPlanWrapper;
//
//    private FormWorkflowService formWorkflowService;
//
//    private IOrgService orgService;
//
//    private IApprovalMessageService approvalMessageService;
//    @Override
//    public boolean saveOrUpdate(EmployementPlan employementPlan) {
//        if (!Optional.ofNullable(employementPlan.getId()).isPresent()) {
//            employementPlan.setCode(formCodeService.getCode(FormTypeConstant.HR_EMPLOYMENT_PLAN));
//            employementPlan.setFormType(String.valueOf(FormTypeConstant.HR_EMPLOYMENT_PLAN));
//        }
//        if (!Optional.ofNullable(employementPlan.getStatus()).isPresent()) {
//            employementPlan.setStatus(FormStatusConstant.UNREVIEWED);
//        }
//        if (employementPlan.getStatus().equals(FormStatusConstant.REJECT)) {
//            employementPlan.setStatus(FormStatusConstant.UNREVIEWED);
//        }
//        return super.saveOrUpdate(employementPlan);
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            EmployementPlan employementPlan = getById(id);
//            if (employementPlan == null) {
//                return false;
//            } else if (employementPlan.getStatus() != null &&
//                    (employementPlan.getStatus() != FormStatusConstant.STASH && employementPlan.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//
//        boolean result = super.deleteLogic(ids);
//        if (result) {
//            employmentDetailService.deleteByParentId(ids);
//        }
//        return result;
//    }
//
//    @Override
//    public boolean submit(EmployementPlan employementPlan) {
//        boolean result = saveOrUpdate(employementPlan);
//        if (result) {
//            List<EmploymentDetail> employmentDetails = employementPlan.getEmploymentDetails();
//            if (CollectionUtil.isNotEmpty(employmentDetails)) {
//                for (EmploymentDetail employmentDetail : employmentDetails) {
//                    employmentDetail.setBasePlanId(employementPlan.getId());
//                    employmentDetail.setDetailType(0);
//                    if (Optional.ofNullable(employmentDetail.getIsDeleted()).isPresent() && employmentDetail.getIsDeleted() == 1) {
//                        employmentDetailService.removeById(employmentDetail.getId());
//                    } else {
//                        employmentDetailService.saveOrUpdate(employmentDetail);
//                    }
//                }
//            }
//        }
//        return result;
//    }
//
//    @Override
//    public EmploymentPlanVO getDetailObj(EmployementPlan employementPlan) {
//        EmploymentPlanVO employmentPlanVO = new EmploymentPlanVO();
//        //获取详情
//        EmployementPlan detail = getOne(Condition.getQueryWrapper(employementPlan));
//        employmentPlanVO = employmentPlanWrapper.entityToVO(detail);
//
//        List<EmploymentDetail> employmentDetails = employmentDetailService.list(new LambdaQueryWrapper<EmploymentDetail>().eq(EmploymentDetail::getBasePlanId, detail.getId()));
//        employmentPlanVO.setEmploymentDetails(employmentDetails);
//        return employmentPlanVO;
//    }
//
//    @Override
//    public ListResult<EmploymentPlanVO> list(@RequestBody Query query) {
//        List<SearchEntity> entityList = query.getSearch();
//        if (query.getAscs() == null && query.getDescs() == null) {
//            query.setDescs("create_time");
//        }
//        QueryWrapper<EmployementPlan> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                Condition.getQueryWrapper(new EmployementPlan()), entityList
//        );
//        TokenSearch<EmployementPlan> tokenSearch = new TokenSearch<>();
//		tokenSearch.addTokenQuery(queryWrapper, query);
//
//        IPage<EmployementPlan> pages = page(Condition.getPage(query), queryWrapper);
//        List<EmploymentPlanVO> employmentPlanVOS = employmentPlanWrapper.entityToVO(pages.getRecords());
//        ListResult<EmploymentPlanVO> listResult = new ListResult<>(CommonCode.SUCCESS);
//        listResult.setList(employmentPlanVOS);
//        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
//        return listResult;
//    }
//
//    @Override
//    public HashMap<String, Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, "");
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String, Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState, comment);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<EmployementPlan> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(EmployementPlan::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<EmployementPlan> employementPlans = list(queryWrapper);
//        List<EmploymentPlanVO> employmentPlanVOS = employmentPlanWrapper.entityToVO(employementPlans);
//        List<PageData> pageDataList = new ArrayList<>();
//        try {
//            if (CollectionUtil.isNotEmpty(employmentPlanVOS)) {
//                for (EmploymentPlanVO vo : employmentPlanVOS) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getFillingUnitName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getFillingUnitId());
//                    pd.put("formType", FormTypeConstant.HR_EMPLOYMENT_PLAN);
//                    pd.put("orgName", vo.getFillingUnitName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.HR_EMPLOYMENT_PLAN);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED, "");
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id           主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus,String comment) {
//        try {
//            EmployementPlan employementPlan = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH) {
//                employementPlan.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                employementPlan.setApprovedTime(now);
//            }
//            if (StringUtil.isNotBlank(employementPlan.getDataSource()) &&
//                    StringUtil.isNotBlank(employementPlan.getDataSourceId())){
//                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
//                    ApprovalMessage approvalMessage = new ApprovalMessage();
//                    approvalMessage.setDataSourceId(employementPlan.getDataSourceId());
//                    approvalMessage.setOpinion(comment);
//                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
//                    approvalMessage.setIsSend(1);
//                    approvalMessage.setDataSourceType(GZW_TYPE);
//
//                    if (employementPlan.getDataSource().equals(YthConstant.DATA_NINGBO)) {
//                        approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
//                        approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
//                        approvalMessage.setFormType(FormTypeConstant.HR_EMPLOYMENT_PLAN);
//                        approvalMessage.setFilingCode(employementPlan.getCode());
//                    }
//                    approvalMessageService.save(approvalMessage);
//                }
//            }
//            employementPlan.setStatus(updateStatus);
//            updateById(employementPlan);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    public R<ReportReturnVO> planExport (EmploymentPlanDTO dto){
//        String name = dto.getCompanyNameId();
//        List<EmploymentPlanExcelVO> employementPlanExcelVOS = new ArrayList<>();
//        List<EmployementPlan> items = list(new LambdaQueryWrapper<EmployementPlan>().like(EmployementPlan::getCompanyNameId, name));
//        if (CollectionUtil.isNotEmpty(items)){
//            for(EmployementPlan employementPlan :items){
//                List<EmploymentDetail> details = employmentDetailService.list(new LambdaQueryWrapper<EmploymentDetail>().eq(EmploymentDetail::getBasePlanId, employementPlan.getId()));
//                EmploymentPlanVO employmentPlanVO = employmentPlanWrapper.entityToVO(employementPlan);
//                EmploymentPlanExcelVO employmentPlanExcelVO = new EmploymentPlanExcelVO();
//                for(EmploymentDetail employmentDetail:details){
//                    employmentPlanExcelVO.setCode(employmentPlanVO.getCode());
//                    employmentPlanExcelVO.setRecruitUnit(employmentPlanVO.getCompanyName());
//                    employmentPlanExcelVO.setPlanAttribute(employmentPlanVO.getPlanAttributeName());
//                    switch (employmentPlanVO.getIsIncreasingCapital()){
//                        case 0:
//                            employmentPlanExcelVO.setIsIncreasingCapital("否");
//                            break;
//                        case 1:
//                            employmentPlanExcelVO.setIsIncreasingCapital("是");
//                            break;
//                        default:
//                            break;
//                    }
//                    switch (employmentPlanVO.getIsIncreasingWorker()){
//                        case 0:
//                            employmentPlanExcelVO.setIsIncreasingWorker("否");
//                            break;
//                        case 1:
//                            employmentPlanExcelVO.setIsIncreasingWorker("是");
//                            break;
//                        default:
//                            break;
//                    }
//                    employmentPlanExcelVO.setDeptName(employmentDetail.getDeptName());
//                    employmentPlanExcelVO.setPosition(employmentDetail.getPosition());
//                    employmentPlanExcelVO.setVacancy(String.valueOf(employmentDetail.getVacancy()));
//                    switch (employmentDetail.getIsHighLevelPersonnel()){
//                        case 0:
//                            employmentPlanExcelVO.setIsHighLevelPersonnel("是");
//                            break;
//                        case 1:
//                            employmentPlanExcelVO.setIsIncreasingWorker("否");
//                            break;
//                        default:
//                            break;
//                    }
//                    switch (employmentDetail.getIsIndex()){
//                        case 0:
//                            employmentPlanExcelVO.setIsIndex("指标内");
//                            break;
//                        case 1:
//                            employmentPlanExcelVO.setIsIndex("指标外");
//                            break;
//                        default:
//                            break;
//                    }
//                    switch (employmentPlanVO.getStatus()){
//                        case 0 :
//                            employmentPlanExcelVO.setStatus("未上报");
//                            break;
//                        case 1 :
//                            employmentPlanExcelVO.setStatus("审批中");
//                            break;
//                        case 2 :
//                            employmentPlanExcelVO.setStatus("驳回");
//                            break;
//                        case 3 :
//                            employmentPlanExcelVO.setStatus("审核通过");
//                            break;
//                        default:
//                            break;
//                    }
//                    employementPlanExcelVOS.add(employmentPlanExcelVO);
//
//                }
//            }
//
//        }
//
//        ReportReturnVO reportReturnVO = new ReportReturnVO();
//        ReportVO reportVO = new ReportVO();
//
//        reportVO
//                .addHeader(HeaderVO.builder().key("code").title("单据编码").build())
//                .addHeader(HeaderVO.builder().key("recruitUnit").title("招聘单位").build())
//                .addHeader(HeaderVO.builder().key("planAttribute").title("计划属性").build())
//                .addHeader(HeaderVO.builder().key("isIncreasingCapital").title("是否属于赠人赠资").build())
//                .addHeader(HeaderVO.builder().key("isIncreasingWorker").title("是否属于补员").build())
//                .addHeader(HeaderVO.builder().key("deptName").title("所属部门").build())
//                .addHeader(HeaderVO.builder().key("position").title("职务岗位").build())
//                .addHeader(HeaderVO.builder().key("vacancy").title("名额").build())
//                .addHeader(HeaderVO.builder().key("isHighLevelPersonnel").title("是否高层次紧缺型人才").build())
//                .addHeader(HeaderVO.builder().key("isIndex").title("指标内（外）").build())
//                .addHeader(HeaderVO.builder().key("Status").title("单据状态").build());
//        reportVO.setData(employementPlanExcelVOS);
//        reportReturnVO.setGrids(reportVO);
//        R<ReportReturnVO> obj =  new R<>(CommonCode.SUCCESS);
//        obj.setPageData(reportReturnVO);
//
//        return obj;
//    }
//
//    public void exportExcel(EmploymentPlanDTO employmentPlanDTO, HttpServletRequest request, HttpServletResponse response)  {
//        R<ReportReturnVO> result = planExport(employmentPlanDTO);
//        ExcelExportUtil excel=new ExcelExportUtil();
//        excel.setTitle("企业用工计划");
//        List<EmploymentPlanExcelVO> reportList = result.getPageData().getGrids().getData();
//        List<Map> list=new ArrayList<>();
//        for(EmploymentPlanExcelVO planExcelVO:reportList){
//            Map m=new HashMap();
//            m.put("code",planExcelVO.getCode());
//            m.put("recruitUnit",planExcelVO.getRecruitUnit());
//            m.put("planAttribute",planExcelVO.getPlanAttribute());
//            m.put("isIncreasingCapital",planExcelVO.getIsIncreasingCapital());
//            m.put("isIncreasingWorker",planExcelVO.getIsIncreasingWorker());
//            m.put("deptName",planExcelVO.getDeptName());
//            m.put("position",planExcelVO.getPosition());
//            m.put("vacancy",planExcelVO.getVacancy());
//            m.put("isHighLevelPersonnel",planExcelVO.getIsHighLevelPersonnel());
//            m.put("isIndex",planExcelVO.getIsIndex());
//            m.put("status",planExcelVO.getStatus());
//
//
//            list.add(m);
//        }
//        excel.setData(list);
//        try {
//            /*String key = StringPool.DASH + UUID.randomUUID().toString().replace(StringPool.DASH, "");
//            String fileName = key + ".xlsx";
//            String exportPath = environment.getProperty("excel.path");
//            File file = new File(exportPath);
//            if (!file.exists()) {
//                file.mkdirs();
//            }*/
//            /*String separator = File.separator;*/
//            String exlPath = "/exceldemo/employmentplan.xlsx";
//            InputStream inputStream = this.getClass().getResourceAsStream(exlPath);
//            String fileName = URLEncoder.encode("employmentplan", "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//            // 设置响应头和客户端保存文件名
//            response.setCharacterEncoding("utf-8");
//            OutputStream outputStream = response.getOutputStream();// 取得输出流
//            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet().build();
//            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//            excelWriter.fill(list, fillConfig, writeSheet);
//            excelWriter.finish();
//            inputStream.close();
//            outputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    @Override
//    public String saveEmploymentPlanList(String data) {
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<EmployementPlan> dataList = JSON.parseArray(data, EmployementPlan.class);
//
//        if (CollectionUtil.isNotEmpty(dataList)) {
//            Map<String, String> orgSourceMap = orgService.getSourceId();
//            //根据datasourceIds 查询出所有的数据
//            List<EmployementPlan> list = list(new LambdaQueryWrapper<EmployementPlan>().eq(EmployementPlan::getDataSource, YthConstant.DATA_NINGBO)
//                    .in(EmployementPlan::getDataSourceId, dataList.stream().map(EmployementPlan::getDataSourceId).toArray()));
//
//            if (CollectionUtil.isNotEmpty(list)) {
//                //删除子集
//                List<Long> ids = list.stream().map(EmployementPlan::getId).collect(Collectors.toList());
//                employmentDetailService.deleteByParentId(ids);
//            }
//            for (EmployementPlan entity:dataList){
//                transfer(entity,orgSourceMap);
//                //id重复略过
//                if (CollectionUtil.isNotEmpty(list)){
//                    List<String> olIds = list.stream().map(EmployementPlan::getDataSourceId).collect(Collectors.toList());
//                    String dataSourceId = entity.getDataSourceId();
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)){
//                        for (EmployementPlan oldEntity:list){
//                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
//                                //判断status是否为0，如果是0，就更新，不是0，就不更新
//                                if (CheckStatus.checkCode(oldEntity.getStatus())) {
//                                    successIds.add(dataSourceId);
//                                    entity.setId(oldEntity.getId());
//                                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                                    submit(entity);
//                                    list.remove(oldEntity);
//                                    break;
//                                }else {
//                                    failIds.add(dataSourceId);
//                                    failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
//                                    break;
//                                }
//                            }
//                        }
//                    }else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//                        submit(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                }else {
//                    //如果数据库中没有数据，就新增
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                    submit(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        }else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    private void transfer(EmployementPlan entity, Map<String, String> orgSourceMap) {
//        Optional.ofNullable(entity.getCompanyNameId()).ifPresent(m ->
//                {
//                    String orgId = orgSourceMap.get(m);
//                    entity.setCompanyNameId(orgId);
//                }
//        );
//
//        Optional.ofNullable(entity.getFillingUnitId()).ifPresent(m ->
//                {
//                    String orgId = orgSourceMap.get(m);
//                    entity.setFillingUnitId(orgId);
//                    entity.setCreateCompanyId(orgId);
//                }
//        );
//
//    }
//
//}
